package com.chat.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.domain.constant.MinioConstant;
import com.chat.domain.pojo.File;
import com.chat.excpetion.CustomException;
import com.chat.mapper.FileMapper;
import com.chat.service.FileService;
import com.chat.util.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lucky
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File>
        implements FileService {


    @Autowired
    private MinioClient minioClient;


    @Override
    public File upload(MultipartFile multipartFile) {
        try {
            // 获取文件名
            String filename = multipartFile.getOriginalFilename();

            long size = multipartFile.getSize();

            // 获取文件名
            String md5 = RandomUtil.randomString(12);
            String generateFilename = generateFilename(multipartFile.getOriginalFilename(), md5);

            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(MinioConstant.BUCKET_NAME)
                    .object(generateFilename)
                    .stream(multipartFile.getInputStream(), size, -1)
                    .build());

            String filePath = MinioConstant.HOST + "/" + MinioConstant.BUCKET_NAME + "/" + generateFilename;

            // 保存文件信息
            File file = new File();
            file.setOriginalName(filename);
            file.setStorageName(generateFilename);
            file.setFilePath(filePath);
            file.setFileSize((int) size);
            file.setFileType(multipartFile.getContentType());
            file.setMd5(md5);
            this.save(file);

            return file;
        } catch (Exception e) {
            throw new CustomException(ResultCodeEnum.FILE_ERROR);
        }
    }


    /**
     * 传入文件名返回新的文件名
     *
     * @param fileName 文件名
     * @return 新的文件名
     */
    public static String generateFilename(String fileName, String md5) {
        if (fileName == null) {
            throw new CustomException(ResultCodeEnum.FILE_NOT_FIND);
        }

        // 获取加密的文件名
        String md5FileName = DigestUtil.md5Hex(fileName + md5);

        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        // 返回新的文件名
        return md5FileName + suffix;
    }
}
